// hooks/useAudioPlay.ts
import { udp } from '@cscec/udp-mobile-ui';
import { useState, useRef, useCallback } from 'react';

interface UseAudioPlayProps {
  per?: string; // 设置音色
  spd?: string; // 设置语速
  onPlayStart?: () => void;
  onPlayEnd?: () => void;
  onError?: (error: string) => void;
}

interface UseAudioPlayReturn {
  isPlaying: boolean;
  isLoading: boolean;
  error: string | null;
  playAudio: (text: string) => Promise<void>;
  stopAudio: () => void;
}

export const useAudioPlay = ({
  per = '4194',
  spd='5',
  onPlayStart,
  onPlayEnd,
  onError
}: UseAudioPlayProps): UseAudioPlayReturn => {
  const [isPlaying, setIsPlaying] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  
  const audioRef = useRef<HTMLAudioElement | null>(null);
  const objectUrlRef = useRef<string | null>(null);

  // 清理音频资源和URL
  const cleanupAudio = useCallback(() => {
    if (objectUrlRef.current) {
      URL.revokeObjectURL(objectUrlRef.current);
      objectUrlRef.current = null;
    }
    if (audioRef.current) {
      audioRef.current.pause();
      audioRef.current = null;
    }
  }, []);

  const playAudio = useCallback(async (text: string) => {
    console.log('播放文本:', text);
    
    if (!text.trim()) {
      setError('请输入要转换的文本');
      return;
    }

    try {
      setIsLoading(true);
      setError(null);
      
      // 停止并清理之前的音频
      cleanupAudio();

      // 添加随机参数避免缓存
      const timestamp = Date.now();
      
      // 调用接口获取音频文件
      const response: any = await udp.request.body({
        url: '/api/admin/getVoice',
        headers: {
          'Content-Type': 'application/json',
        },
        data: {
          text: text,//字符传
          per:per,//音色列表度涵竹=4189，度嫣然=4194，度泽言=4193，度怀安=4195，度清影=4196，度沁遥=4197，
          vol:'5',//音量，基础音库取值0-9，精品音库取值0-15，默认为5中音量（取值为0时为音量最小值，并非为无声）
          pit:'5',//音调，取值0-15，默认为5中语调
          spd:spd,//语速，取值0-15，默认为5中语速
           //_t: timestamp,// 添加防缓存参数
          // _r: random
          },
      });

      if (response.code !== 200) {
        throw new Error(`请求失败: ${response.msg}`);
      }
      // 方法1: 如果返回的是音频URL，添加时间戳参数
      let audioUrl = response.data;
      if (typeof audioUrl === 'string') {
        // 在URL后添加时间戳参数避免缓存
        const separator = audioUrl.includes('?') ? '&' : '?';
        audioUrl = `${audioUrl}${separator}_t=${timestamp}`;
      }

      // 创建音频元素
      const audio = new Audio(audioUrl);
      audioRef.current = audio;

      // 设置音频事件监听器
      audio.onplay = () => {
        setIsPlaying(true);
        setIsLoading(false);
        onPlayStart?.();
      };

      audio.onended = () => {
        setIsPlaying(false);
        onPlayEnd?.();
        cleanupAudio();
      };

      audio.onerror = (e) => {
        console.error('音频播放错误:', e);
        setIsPlaying(false);
        setIsLoading(false);
        const errorMsg = `音频播放失败: ${audio.error?.message || '未知错误'}`;
        setError(errorMsg);
        onError?.(errorMsg);
        cleanupAudio();
      };

      audio.oncanplaythrough = () => {
        setIsLoading(false);
      };

      // 开始播放
      await audio.play();

    } catch (err) {
      console.error('音频播放异常:', err);
      const errorMsg = err instanceof Error ? err.message : '音频转换失败';
      setError(errorMsg);
      onError?.(errorMsg);
      setIsLoading(false);
      cleanupAudio();
    }
  }, [per, onPlayStart, onPlayEnd, onError, cleanupAudio]);

  const stopAudio = useCallback(() => {
    setIsPlaying(false);
    setIsLoading(false);
    cleanupAudio();
  }, [cleanupAudio]);

  return {
    isPlaying,
    isLoading,
    error,
    playAudio,
    stopAudio,
  };
};